from src.models.BaseModel import BaseModel
from peewee import *
from src.util.Model2Dict import m2d
from src.entry.Entrys import Page


class SysConfig(BaseModel):
    key = CharField(primary_key=True)
    name = CharField()
    value = CharField()
    type = CharField()

    class Meta:
        table_name = 'sys_config'

    # #config
    # 获取所有的配置信息 cType 可以通过list 查询
    @staticmethod
    def getAllConfig(page: Page = None, cdn: dict = None):
        if cdn is None:
            cdn = dict()
        q = SysConfig.select(SysConfig.key, SysConfig.value)
        if page:
            r = q.paginate(page.num, page.size).dicts()
            page.count = q.count()
            page.rows = m2d(r)
            return page.__dict__
        cType = cdn.get('type')
        if cType:
            if type(cType) == str:
                q = q.where(SysConfig.type == cType)
            elif type(cType) == list:
                q = q.where(SysConfig.type.in_(cType))
        r = q.dicts()
        return m2d(r)

    """ 根据key获取某配置信息 """

    @staticmethod
    def getConfigByKey(key: str, c_type='user'):
        r = SysConfig.select(SysConfig.value).where(SysConfig.key == key, SysConfig.type == c_type).dicts()
        if len(r) > 0:
            return m2d(r)[0]
        return None

    """ 根据key更新配置信息的属性 """

    @staticmethod
    def updateConfigByKey(key: str, k: dict, c_type: list[str] | str = 'user'):
        q = SysConfig.update({'value': k})
        if type(c_type) == str:
            q = q.where(SysConfig.type == c_type)
        elif type(c_type) == list:
            q = q.where(SysConfig.type.in_(c_type))
        q.where(SysConfig.key == key).execute()
        return True

    """ 添加配置信息 """

    @staticmethod
    def addConfig(d: dict):
        return SysConfig.insert(d).execute()

    @staticmethod
    def delConfig(keys: list[str]):
        q = SysConfig.delete()
        q.where(SysConfig.key.in_(keys)).execute()
        return True


class SysDict(BaseModel):
    dId = BigIntegerField(column_name='d_id', primary_key=True)
    status = CharField()
    initTime = DateTimeField(column_name='init_time')
    type = CharField()
    path = CharField()
    name = CharField()
    description = CharField()

    class Meta:
        table_name = 'sys_dict'

    # ##dict
    """ 获取所有的字典 """

    @staticmethod
    def getAllDict(page: Page = Page(), cdn: dict = None):
        if cdn is None:
            cdn = dict()
        query = SysDict.select()
        if cdn.get('path'):
            query = query.where(SysDict.path.startswith(cdn.get('path')))
        if cdn.get('type'):
            query = query.where(SysDict.type == cdn.get('type'))
        if cdn.get('name'):
            query = query.where(SysDict.name.contains(cdn.get('name')))
        if cdn.get('status'):
            query = query.where(SysDict.status == cdn.get('status'))
        if cdn.get('initTime'):
            start = cdn.get('initTime')[0]
            end = cdn.get('initTime')[1]
            query = query.where((SysDict.initTime >= start) & (SysDict.initTime <= end))
        r = query.paginate(page.num, page.size).dicts()
        page.count = query.count()
        page.rows = m2d(r)
        return page.__dict__

    """ 根据path获取SysDict"""

    @staticmethod
    def getDictByPathAndTYpe(path: str, d_type: str):
        r = SysDict.select().where(SysDict.path == path, SysDict.type == d_type).dicts()
        if len(r) == 0:
            return None
        return m2d(r)[0]

    """ 更新字典的属性 """

    @staticmethod
    def updateDict(id: int, k) -> bool:
        return SysDict.update(k).where(SysDict.dId == id).execute() > 0

    """ 删除字典 """

    @staticmethod
    def delDictById(d_ids: list[int]):
        return SysDict.delete().where(SysDict.dId.in_(d_ids)).execute() > 0

    """ 添加字典 """

    @staticmethod
    def addDict(d: dict):
        return SysDict.insert(d).execute()


""" 字典key和value """


class DictKeyValue(BaseModel):
    id = BigIntegerField(column_name='id', primary_key=True)
    dId = BigIntegerField(db_column='d_id')
    key = CharField(column_name='key')
    val = CharField()

    class Meta:
        table_name = "sys_dict_kv"

    """ 根据did获取DictKeyValue表的kv"""

    @staticmethod
    def getKvByDid(did):
        r = DictKeyValue.select(DictKeyValue.key, DictKeyValue.val).where(DictKeyValue.dId == did).dicts()
        return m2d(r)

    """ 删除所有有did 的映射关系 """

    @staticmethod
    def delDictKeyValueByDid(d_ids: list[int]):
        return DictKeyValue.delete().where(DictKeyValue.dId.in_(d_ids)).execute()

    """ 添加字典KV """

    @staticmethod
    def addDictKv(d: list[dict]):
        return DictKeyValue.insert_many(d).execute()
